package ar.com.telefonica.fwk.impl;

import java.util.Collection;
import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import ar.com.telefonica.fwk.DAO;
import ar.com.telefonica.fwk.Persistent;

/**
 * @author Abel Fillol
 *
 */
public abstract class DAOAbstract<T  extends Persistent> extends HibernateDaoSupport implements DAO<T>{

	protected abstract Class<? extends T> getClassMapped();

	@Override
	@SuppressWarnings("unchecked")
	public T getById(Integer id) {
		Session session = this.getCurrentSession();
		return (T) session.get(this.getClassMapped(), id);
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public T loadById(Integer id) {
		Session session = this.getCurrentSession();
		return (T) session.load(this.getClassMapped(), id);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Collection<T> findAll() {
		Session session = this.getCurrentSession();
		Collection<T> result = session.createQuery("from " + this.getClassMapped().getName()).list();
		return result;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public Iterator<T> findAllIterator() {
		Session session = this.getCurrentSession();
		Iterator<T> iterator = session.createQuery("from " + this.getClassMapped().getName()).iterate();
		return iterator;
	}

	@Override
	public void save(T instance) {
		Session session = this.getCurrentSession();
		session.save(instance);
	}

	@Override
	public void delete(T instance) {
		Session session = this.getCurrentSession();
		session.delete(instance);
	}
	
	protected Query generateQuery(String where){
		Session session = this.getCurrentSession();
		return session.createQuery("from " + this.getClassMapped().getCanonicalName() + " where " + where);
	}
	
	/**
	 * TODO: Verificar que no se crucen las transacciones cuando mas de un thread est� usando el 
	 * mismo DAO
	 * @return
	 */
	private Session getCurrentSession() {
		Session session = this.getSessionFactory().getCurrentSession();
		if (!session.getTransaction().isActive()){
			session.beginTransaction();
		}
		return session;
	}
}